package com.alibaba.citrus.ots.forecast.functions.forecastorder.ability;

import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.otsforecastsales.dto.request.QueryGoodsDetailRequest;
import com.epoch.app.otsforecastsales.model.dto.GiftSDO;
import com.epoch.app.otsforecastsales.model.dto.SubOrderInfo;
import com.epoch.app.otsforecastsales.sdo.ForecastOrderSDO;
import com.epoch.app.otsforecastsales.sdo.MainOrderInfo;
import com.epoch.app.otspricecenter.api.pricequery.service.PriceQueryService;
import com.epoch.app.otspricecenter.dto.request.*;
import com.epoch.app.otspricecenter.dto.response.ItemPriceResponse;
import com.epoch.app.otspricecenter.dto.response.PriceQueryResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author: qiaojiange
 * @create: 2021/12/10
 * @Description 请描述类的业务用途
 */
@Component
public class PriceQueryUtils {

    private static  Log log = Log.getLogger(PriceQueryUtils.class);

    /**
     * 内外码转换 key
     */
    private static String CODE_FLAG = "codeFlag";
    /**
     * 内外码转换 value
     */
    private static String INNER_CODE_TO_OUT_CODE = "inner_code_to_out_code";

    @Resource
    private PriceQueryService priceQueryService;

    @ProcessInvoker(printLog = true)
    public List<SubOrderInfo> queryGoodsDetail(QueryGoodsDetailRequest queryGoodsDetailResponseRequest) {
        MainOrderInfo forecastOrderSDO = queryGoodsDetailResponseRequest.getForecastOrderSDO();
        List<SubOrderInfo> forecastOrderLineSDOList = null;
        if (CollectionUtils.isNotEmpty(forecastOrderSDO.getForecastOrderLineSDOList())) {
            forecastOrderLineSDOList = forecastOrderSDO.getForecastOrderLineSDOList();
            PriceQueryRequest priceQueryRequest = new PriceQueryRequest();

            List<DimensionPropertyInfoRequest> dimensionPropertyInfoRequestList = new ArrayList<>();

            for (SubOrderInfo subOrderInfo : forecastOrderLineSDOList) {
                //转换参数
                String firstCategoryCode = null;
                String firstCategoryDesc = null;
                String secondCategoryCode = null;
                String secondCategoryDesc = null;

                if (StringUtils.isNotBlank(subOrderInfo.getIdPath())) {
                    String[] categoryIds = subOrderInfo.getIdPath().split(">>");

                    firstCategoryCode = categoryIds[0] == null ? null : categoryIds[0];
                    if (categoryIds.length >= 2) {
                        secondCategoryCode = categoryIds[1] == null ? null : categoryIds[1];
                    }

                }
                if (StringUtils.isNotBlank(subOrderInfo.getCurrentPath())) {
                    String[] categoryDescList = subOrderInfo.getCurrentPath().split(">>");
                    firstCategoryDesc = categoryDescList[0] == null ? null : categoryDescList[0];
                    if (categoryDescList.length >= 2) {
                        secondCategoryDesc = categoryDescList[1] == null ? null : categoryDescList[1];
                    }

                }
                subOrderInfo.setFirstCategoryCode(firstCategoryCode);
                subOrderInfo.setFirstCategoryDesc(firstCategoryDesc);
                subOrderInfo.setSecondCategoryCode(secondCategoryCode);
                subOrderInfo.setSecondCategoryDesc(secondCategoryDesc);

                DimensionPropertyInfoRequest dimensionPropertyInfoRequest = new DimensionPropertyInfoRequest();
                dimensionPropertyInfoRequest.setPriceTypeId("ZP01");
                dimensionPropertyInfoRequest.setPriceUseDate(new Date());

                //货品组
                MaterialInfoRequest materialInfoRequest = new MaterialInfoRequest();
                materialInfoRequest.setMaterialCode(subOrderInfo.getScItemId());

                materialInfoRequest.setScItemGroupCode(forecastOrderSDO.getProductGroupCode());
                HumanInfoRequest humanInfoRequest = new HumanInfoRequest();
                //客户
                humanInfoRequest.setCustomerCode(forecastOrderSDO.getCustomerCode());
                humanInfoRequest.setCustomerSendAddressCode(forecastOrderSDO.getReceiveAddressCode());
                humanInfoRequest.setCustomerSaleAddressCode(forecastOrderSDO.getCustomerCode());
                PlaceInfoRequest placeInfoRequest = new PlaceInfoRequest();
                placeInfoRequest.setChannelCode(forecastOrderSDO.getChannelCode());
                placeInfoRequest.setDepartmentCode(forecastOrderSDO.getDepartmentCode());
                placeInfoRequest.setSalesUnitCode(subOrderInfo.getSaleUnitCode());
                placeInfoRequest.setOrgSalesOrganizationCode(queryGoodsDetailResponseRequest.getForecastOrderSDO().getOrganizationCode());


                dimensionPropertyInfoRequest.setMaterialInfoRequest(materialInfoRequest);
                dimensionPropertyInfoRequest.setHumanInfoRequest(humanInfoRequest);
                dimensionPropertyInfoRequest.setPlaceInfoRequest(placeInfoRequest);

                dimensionPropertyInfoRequestList.add(dimensionPropertyInfoRequest);
            }
            Map<String, String> features = new HashMap<>();
            features.put("codeFlag", "inner_code_to_out_code");
            priceQueryRequest.setDimensionPropertyInfoRequestList(dimensionPropertyInfoRequestList);
            priceQueryRequest.setFeatures(features);
            Result<PriceQueryResponse> priceQueryResponseResult = priceQueryService.batchQueryPriceExpand(priceQueryRequest);
            if (!priceQueryResponseResult.isSuccess() || CollectionUtils.isEmpty(priceQueryResponseResult.getResult().getItemPriceResponseList())) {
                return forecastOrderLineSDOList;
            }
            PriceQueryResponse result = priceQueryResponseResult.getResult();


            //Map<String,Long> itemPriceMap = result.getItemPriceResponseList().stream().collect(Collectors.toMap(ItemPriceResponse::getItemId,ItemPriceResponse::getMoneyAmout));
            Map<String, Long> itemPriceMap = result.getItemPriceResponseList().stream().collect(HashMap::new, (m, v) -> m.put(v.getItemId(), v.getMoneyAmout()), HashMap::putAll);
            for (SubOrderInfo forecastOrderLineSDO : forecastOrderLineSDOList) {
                forecastOrderLineSDO.setUnitPrice(itemPriceMap.get(forecastOrderLineSDO.getScItemId()));
            }



        }
        return forecastOrderLineSDOList;
    }


    /**
     * 获取赠品价格
     * @param forecastOrderSDO 主单信息
     * @param giftSDO 赠品信息
     * @return
     */
    @ProcessInvoker
    public Long obtainGiftPrice(ForecastOrderSDO forecastOrderSDO, GiftSDO giftSDO) {
        //一 获取价格
        PriceQueryRequest priceQueryRequest = new PriceQueryRequest();
        List<DimensionPropertyInfoRequest> dimensionPropertyInfoList = new ArrayList<>();
        DimensionPropertyInfoRequest dimensionPropertyInfoRequest = new DimensionPropertyInfoRequest();
        //价格类型
        dimensionPropertyInfoRequest.setPriceTypeId("ZP01");
        //价格使用时间
        dimensionPropertyInfoRequest.setPriceUseDate(new Date());


        PlaceInfoRequest placeInfoRequest = new PlaceInfoRequest();
        placeInfoRequest.setChannelCode(forecastOrderSDO.getChannelCode());
        placeInfoRequest.setDepartmentCode(forecastOrderSDO.getDepartmentCode());
        placeInfoRequest.setSalesUnitCode(giftSDO.getGiftSalesUnitCode());
        placeInfoRequest.setOrgSalesOrganizationCode(forecastOrderSDO.getOrganizationCode());


        //货的信息
        MaterialInfoRequest materialInfoRequest = new MaterialInfoRequest();
        //货品编码（ SAP物料编码）
        materialInfoRequest.setMaterialCode(giftSDO.getScItemId());
        //产品组编码 货品组
        materialInfoRequest.setScItemGroupCode(forecastOrderSDO.getProductGroupCode());


        // 人的信息
        HumanInfoRequest humanInfoRequest = new HumanInfoRequest();
        //客户编码
        humanInfoRequest.setCustomerCode(forecastOrderSDO.getCustomerCode());
        //售达方编码 客户编码（SAP售达方编码）
        humanInfoRequest.setCustomerSaleAddressCode(forecastOrderSDO.getWareHouseCode());
        //
        humanInfoRequest.setCustomerSendAddressCode(forecastOrderSDO.getWareHouseCode());
        //客户收货地址编码（SAP 送达方编码）
        humanInfoRequest.setCustomerSendAddressCode(forecastOrderSDO.getReceiveAddressCode());
        //价目清单编码 (从客户信息上取)
        humanInfoRequest.setCustomerSaleAddressCode(forecastOrderSDO.getCustomerCode());

        dimensionPropertyInfoRequest.setMaterialInfoRequest(materialInfoRequest);
        dimensionPropertyInfoRequest.setHumanInfoRequest(humanInfoRequest);
        dimensionPropertyInfoRequest.setPlaceInfoRequest(placeInfoRequest);

        //添加维度
        dimensionPropertyInfoList.add(dimensionPropertyInfoRequest);
        priceQueryRequest.setDimensionPropertyInfoRequestList(dimensionPropertyInfoList);
        Long moneyAmount = 0L;
        log.info("主单ID={},赠品 ID={},查询赠品价格!", forecastOrderSDO.getId(), giftSDO.getScItemId());
        Map<String, String> map = new HashMap<>();
        map.put(CODE_FLAG, INNER_CODE_TO_OUT_CODE);
        priceQueryRequest.setFeatures(map);
        log.info("查询价格入参：",priceQueryRequest);
        Result<PriceQueryResponse> priceQueryResponseResult = priceQueryService.batchQueryPriceExpand(priceQueryRequest);
        if (!priceQueryResponseResult.isSuccess() || priceQueryResponseResult.getResult() == null) {
            return -1L;
        }
        List<ItemPriceResponse> itemPriceResponseList = priceQueryResponseResult.getResult().getItemPriceResponseList();
        ItemPriceResponse itemPriceResponse = itemPriceResponseList.get(0);
        moneyAmount = itemPriceResponse.getMoneyAmout();
        return moneyAmount;
    }
}
